const express = require('express');
const router = express.Router();
const MySQL = require('../../mysql/mysql');
const Log = require('../../common/log');
const bodyParser = require('body-parser');
const MD5 = require('md5');
const Common = require("../../common/common");
const ResList = require('../../common/responseList');

// 配置body-parser
router.use(bodyParser.urlencoded({
	extended: true
}));
router.use(bodyParser.json());

/**
 * 用户登录
 * 接收客户端传入的登录信息
 * 返回登录结果
 */
router.post('/login.node', (req, res) => {
	// 获取客户端数据
	let loginData = {
		UserName: req.body.UserName,
		PassWord: MD5(req.body.PassWord)
	}

	// 处理客户端请求的数据
	if (loginData.UserName && loginData.PassWord) {
		// 验证用户名是否存在
		let sql = "select * from t_user where UserName = " + MySQL.mysql.escape(loginData.UserName);
		MySQL.Mysql(sql, {}, (err, results, fileds) => {
			if (err) {
				throw err;
				// 响应客户端
				ResList.ResList(req, res, '1', '登录失败', {});
				// 记录日志
				Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '1', '登录失败','');
			} else {
				//用户名在数据库不存在
				if (results.length == 0) {
					// 响应客户端
					ResList.ResList(req, res, '-3', '用户不存在', {});
					// 记录日志
					Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '-3', '用户不存在','');
				} else {
					// 验证该用户名在数据库对应的密码是否与客户端传入的密码完全相等
					if (results[0].PassWord === loginData.PassWord) {
						// 响应客户端
						ResList.ResList(req, res, '0', '登录成功', results);
						// 记录日志
						Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '0', '登录成功','');
					} else {
						// 响应客户端
						ResList.ResList(req, res, '1', '用户名或密码错误', {});
						// 记录日志
						Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '1', '用户名或密码错误','');
					}
				}
			}
		})
	} else {
		// 响应客户端
		ResList.ResList(req, res, '-2', '空指针异常', {});
		// 记录日志
		Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '-2', '空指针异常','');
	}


})

module.exports = router;